#include "./include/loginDlg.h"
#include "include/addUsr.h"

#include <QtGui>
#include <QSqlDatabase>
#include <QSqlQuery>

LoginDlg::LoginDlg(QWidget *parent)
    : QDialog(parent)
{
    setWindowFlags(Qt::FramelessWindowHint);
    setFixedSize(360, 180);
    setWindowTitle(QString::fromUtf8("登录"));

    CreateWidget();
}

void LoginDlg::CreateWidget()
{
    bannerLabel = new QLabel(QString::fromUtf8("管理员登录"), this);
    QFont tmpFont = bannerLabel->font();
    tmpFont.setPointSize(18);
    tmpFont.setBold(true);
    bannerLabel->setFont(tmpFont);

    usrNameLabel = new QLabel(QString::fromUtf8("用户名:"), this);
    pwdLabel = new QLabel(QString::fromUtf8(" 密码:"), this);
    usrNameLineEdit = new QLineEdit(this);
    pwdLineEdit = new QLineEdit(this);
    addUsrBtn = new QPushButton(QString::fromUtf8("新增"), this);
    loginBtn = new QPushButton(QString::fromUtf8("登录"), this);
    cancleBtn = new QPushButton(QString::fromUtf8("取消"), this);

    loginBtn->setFocus();

    pwdLineEdit->setEchoMode(QLineEdit::Password);

    connect(addUsrBtn, SIGNAL(clicked()), this, SLOT(Addusr()));
    connect(loginBtn, SIGNAL(clicked()), this, SLOT(Login()));
    connect(cancleBtn, SIGNAL(clicked()), this, SLOT(close()));
}

void LoginDlg::paintEvent(QPaintEvent *)
{
    QPainter painterLine(this);
    painterLine.drawLine(0, 41, 360, 41);

    QPainter painterRect(this);
    painterRect.setPen(Qt::white);
    painterRect.setBrush(Qt::white);
    painterRect.drawRect(0, 0, 360, 40);
    painterRect.drawRect(0, 145, 360, 180);

    bannerLabel->setGeometry(105, 7, 200, 30);
    usrNameLabel->setGeometry(20, 60, 50, 24);
    usrNameLineEdit->setGeometry(80, 60, 200, 24);
    pwdLabel->setGeometry(28, 100, 50, 24);
    pwdLineEdit->setGeometry(80, 100, 200, 24);
    addUsrBtn->setGeometry(5, 150, 50, 24);
    loginBtn->setGeometry(240, 150, 50, 24);
    cancleBtn->setGeometry(300, 150, 50, 24);
}

void LoginDlg::Addusr()
{
    this->hide();
    AddUsr *add = new AddUsr();
    if(add->exec() == QDialog::Accepted)
    {
        this->show();
    }
}

bool LoginDlg::Login()
{
    bool isRight = false;

    usrName = usrNameLineEdit->text();
    pwd = pwdLineEdit->text();
    if(usrName == "" || pwd == "")
    {
        qDebug() << "用户名或密码不能为空";
        return false;
    }

    QSqlDatabase::database().transaction();
    QSqlQuery query;

    query.exec(QString("select usrName, passWord from usrInfo where usrName = '%1' and passWord = '%2'").arg(usrName).arg(pwd));
    while(query.next())
    {
        isRight = true;
    }
    QSqlDatabase::database().commit();

    qDebug() << isRight;

    if(isRight)
    {
        accept();

    }
}
